package com.example.zhongyingkaoshi.service;

import com.example.zhongyingkaoshi.controller.EmailSender;
import com.example.zhongyingkaoshi.entity.ExamInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
public class ExamStatsService {
    private static final String DB_URL = "jdbc:mysql://192.168.201.177:3306/juanwang";
    private static final String DB_USER = "juanwang";
    private static final String DB_PASSWORD = "fjfdzJ2sXjNPJJXa";
    
    // 存储考试信息的Map
    private final Map<LocalDate, List<ExamInfo>> examInfos = new ConcurrentHashMap<>();
    
    
    @Autowired
    private EmailSender emailSender;

    // 即时发送邮件
    public void sendImmediateReport() throws javax.mail.MessagingException {
        LocalDate today = LocalDate.now();
        if (examInfos.containsKey(today)) {
            List<ExamInfo> infos = examInfos.get(today);
            // 使用相同的邮件内容构造逻辑
            StringBuilder emailContent = new StringBuilder("即时考试成绩汇总：\n");
            double totalScore = infos.stream().mapToDouble(ExamInfo::getScore).sum();
            
            infos.forEach(info -> emailContent.append(String.format(
                "日期: %s, 姓名: %s, 科目: %s, 分数: %.1f%n",
                info.getDate(), info.getExaminee(), info.getSubject(), info.getScore()
            )));
            
            emailContent.append(String.format("总成绩: %.1f", totalScore));
            
            if (emailSender != null && !infos.isEmpty()) {
                emailSender.sendEmail("成绩报告", emailContent.toString());
            }
        }
    }

    public void performDailyStats() {
        LocalDate today = LocalDate.now();
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            //SQL查询样例
            String sql = "SELECT t.exam_score, t.update_at, acc.auth_account "
                    + "FROM t_answer t "
                    + "JOIN t_account acc ON t.create_by = acc.user_id "
                    + "WHERE DATE(t.update_at) = ?";
            
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setDate(1, java.sql.Date.valueOf(today));
                
                try (ResultSet rs = pstmt.executeQuery()) {
                    List<ExamInfo> todayInfos = new ArrayList<>();
                    while (rs.next()) {
                        LocalDate examDate = rs.getDate("update_at").toLocalDate();
                        String examinee = rs.getString("auth_account");
                        double score = rs.getDouble("exam_score");
                        
                        todayInfos.add(new ExamInfo(examDate, examinee, "默认科目", score));
                    }
                    if (!todayInfos.isEmpty()) {
                        examInfos.put(today, todayInfos);
                    }
                }
            }

            // 7天前数据汇总逻辑
            LocalDate sevenDaysAgo = today.minusDays(7);
            if (examInfos.containsKey(sevenDaysAgo)) {
                List<ExamInfo> infos = examInfos.get(sevenDaysAgo);
                StringBuilder emailContent = new StringBuilder("7天考试成绩汇总：\n");
                double totalScore = infos.stream().mapToDouble(ExamInfo::getScore).sum();
                
                infos.forEach(info -> emailContent.append(String.format(
                    "日期: %s, 考生: %s, 科目: %s, 分数: %.1f%n",
                    info.getDate(), info.getExaminee(), info.getSubject(), info.getScore()
                )));
                
                emailContent.append(String.format("总成绩: %.1f", totalScore));
                
                // 调用邮件服务
                // 邮件发送
                if (emailSender != null && !infos.isEmpty()) {
                    // 修改调用方式（去掉静态调用）
                    emailSender.sendEmail("7天成绩汇总报告", emailContent.toString());
                    examInfos.remove(sevenDaysAgo); // 添加数据清理操作
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}